/* 使用本组件需传type，为1获取班级动态   2获取学校动态 */

import React, { memo, Component } from 'react'
import { getClassComments, sendClassComment, addConnection } from '@/api/user'
import { getDateDiff } from '@/utils/tool'
import { baseUrl } from '../../assets/baseUrl'
import { StudentInfo } from '../../utils/model'
import { Form, Input, Button, message, Popover, Divider } from 'antd'
import './index.css'
const BaseUrl = baseUrl()
const { TextArea } = Input
class comments extends Component {
  static contextType = StudentInfo
  constructor(props) {
    super(props)
    this.state = {
      userInfo: props.userInfo, //用来存用户信息
      classId: props.userInfo.classId,
      schoolId: props.userInfo.schoolId,
      commentList: [], //userType为用户类型，1-会员 ，2-超级会员 ， 99-官方人员
      commentSend: '', //发动态文本域内容
      sendDown: false, //勿动，与发动态动画相关
      startNum: null, //页面尾动态对应number
      pageCount: 5, //每次上拉加载获取评论条数    这里可变
      studentId: null
    }
  }
  componentDidMount() {
    this.setState({
      studentId: this.context?.studentInfo?.studentId
    },()=>{
      window.addEventListener('scroll', this.handleScroll, false)
      this.getClassComment()
    })
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll)
  }

  getScrollTop = () => {
    var scrollTop = 0,
      bodyScrollTop = 0,
      documentScrollTop = 0
    if (document.body) {
      bodyScrollTop = document.body.scrollTop
    }
    if (document.documentElement) {
      documentScrollTop = document.documentElement.scrollTop
    }
    scrollTop =
      bodyScrollTop - documentScrollTop > 0 ? bodyScrollTop : documentScrollTop
    return scrollTop
  }

  getScrollHeight = () => {
    var scrollHeight = 0,
      bodyScrollHeight = 0,
      documentScrollHeight = 0
    if (document.body) {
      bodyScrollHeight = document.body.scrollHeight
    }
    if (document.documentElement) {
      documentScrollHeight = document.documentElement.scrollHeight
    }
    scrollHeight =
      bodyScrollHeight - documentScrollHeight > 0
        ? bodyScrollHeight
        : documentScrollHeight
    return scrollHeight
  }

  getWindowHeight = () => {
    var windowHeight = 0
    if (document.compatMode == 'CSS1Compat') {
      windowHeight = document.documentElement.clientHeight
    } else {
      windowHeight = document.body.clientHeight
    }
    return windowHeight
  }

  // 页面滚动
  handleScroll = () => {
    if (
      this.getScrollHeight() - this.getScrollTop() - this.getWindowHeight() <
      10
    ) {
      // 解除绑定
      window.removeEventListener('scroll', this.handleScroll, false)
      // 在这里发送请求
      console.log('到底了')
      this.getClassComment()
      // 并在请求到数据后重新开启监听
      // setTimeout(()=>window.addEventListener('scroll', this.handleScroll, false), 300)
    }
  }

  /* 获取评论 */
  getClassComment = () => {
    let { startNum, pageCount, classId, schoolId } = this.state
    getClassComments({startNum, pageCount, classId, schoolId}).then((res) => {
      let comment = res.data?.data
      let { commentList } = this.state
      window.addEventListener('scroll', this.handleScroll, false) //请求到数据后重新开启滚动监听
      if (startNum === null) {
        this.setState({
          startNum: res.data?.startNum,
          commentList: [...comment]
        })
      } else {
        if (res.data.startNum < 0) {
          message.warning('没有更多啦！')
          window.removeEventListener('scroll', this.handleScroll, false)
        }
        this.setState({
          startNum: res.data.startNum,
          commentList: [...commentList, ...comment]
        })
      }
    })
  }

  onFinish = (values) => {
    let { commentSend } = this.state
    let createTime = Date.parse(new Date())
    let content = commentSend
    if (content.replace(/\s+/g, '') === '') {
      message.warning('内容不能为空或纯空格!')
      return
    } else if (content.length > 255) {
      message.warning('内容过长，请上传图片!')
      return
    }
    this.setState({
      sendDown: true,
      startNum: null
    })
    let data = {
      createTime: createTime,
      content: content
    }
    sendClassComment(data).then((res) => {
      this.getClassComment()
      setTimeout(
        () =>
          this.setState({
            sendDown: false,
            commentSend: ''
          }),
        1000
      )
    })
  }

  onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo)
  }

  //添加聊天对象
  addConnecter(hisStudentId) {
    localStorage.setItem('closeIcon', true)
    addConnection({
      hisStudentId: hisStudentId
    })
  }
  render() {
    const { commentList, commentSend, sendDown, studentId } = this.state
    return (
      <div className="flex" style={{ width: '100vw' }}>
        <div
          style={{
            width: '50%',
            minWidth: '300px',
            padding: '40px 24px',
            marginTop: 30,
            marginLeft: '25%'
          }}
        >
          {commentList.map((item) => {
            //评论列表
            return (
              <div
                className={sendDown ? 'wendown' : ''}
                style={{
                  marginBottom: 30,
                  padding: '15px 0 0 24px',
                  background: 'rgba(255, 255, 255,.7)',
                  borderRadius: 16
                }}
              >
                <div className="flex">
                  <div style={{ position: 'relative' }}>
                    {
                      <Popover
                        placement="topLeft"
                        content={
                          item.studentId == studentId ? (
                            <div>我的动态</div>
                          ) : (
                            <div
                              className="addConnection"
                              onClick={this.addConnecter.bind(
                                this,
                                item.studentId
                              )}
                            >
                              发起聊天
                            </div>
                          )
                        }
                      >
                        {item?.headPicUrl ? (
                          <img
                            src={BaseUrl + item?.headPicUrl}
                            alt=""
                            style={{
                              //有头像就用用户头像
                              width: 48,
                              height: 48,
                              borderRadius: '50%',
                              border: 'none'
                            }}
                          />
                        ) : (
                          <img
                            src={BaseUrl + 'headpic.png'}
                            alt=""
                            style={{
                              //没有头像就用默认头像
                              width: 48,
                              height: 48,
                              borderRadius: '50%',
                              border: 'none'
                            }}
                          />
                        )}{' '}
                      </Popover>
                    }
                    <div
                      style={{
                        position: 'absolute',
                        bottom: -5,
                        right: 0
                      }}
                    >
                      {item?.userType === 1 && (
                        <i
                          className="iconfont icon-huiyuanvip" //用户类型为1 ，用vip图标
                          style={{
                            color: 'red',
                            border: '1px solid white',
                            borderRadius: '50%'
                          }}
                        ></i>
                      )}
                      {item?.userType === 2 && (
                        <i
                          className="iconfont icon-SVIP-fill" //用户类型为1 ，用vip图标
                          style={{
                            color: 'yellow'
                          }}
                        ></i>
                      )}
                      {item?.userType === 99 && (
                        <i
                          className="iconfont icon-renzheng" //用户类型为1 ，用vip图标
                          style={{
                            color: 'green'
                          }}
                        ></i>
                      )}
                    </div>
                  </div>
                  <div className="pl-3">
                    <div
                      className={
                        item?.userType === 1
                          ? 'font-semibold text-red-500'
                          : item?.userType === 2
                          ? 'font-semibold text-yellow-300'
                          : item?.userType === 99
                          ? 'font-semibold text-green-600'
                          : 'font-semibold'
                      }
                      style={{ fontSize: 14, fontWeight: 450 }}
                    >
                      {item.nickName}
                      {/* <div style={{
                                                        display:'inline-block',
                                                        color:'red',
                                                        fontSize:10
                                                    }}>
                                                            vip
                                                    </div> */}
                    </div>
                    <div className="pt-2 text-gray-600 text-xs">
                      {getDateDiff(item.createTime)}
                    </div>
                  </div>
                </div>
                <div
                  className="text-gray-700"
                  style={{
                    padding: '20px 5px 30px 50px'
                  }}
                >
                  {item.content}
                </div>
              </div>
            )
          })}
          <Divider>到底啦</Divider>
        </div>
        <div>
          <div
            className={sendDown ? 'keyrun' : ''}
            style={{
              width: '23%',
              height: '75vh',
              marginTop: '70px',
              background: 'rgba(255, 255, 255,.7)',
              borderRadius: 16,
              position: 'fixed',
              right: '2%',
              padding: '24px 0'
            }}
          >
            <div>
              <Form
                className={sendDown ? 'out' : ''}
                style={{ padding: '0 24px' }}
                onFinish={this.onFinish.bind(this)}
                onFinishFailed={this.onFinishFailed.bind(this)}
              >
                <Form.Item
                  label="动态"
                  validateStatus={commentSend.length > 255 ? 'error' : ''}
                  style={{
                    width: '100%'
                  }}
                  help={
                    commentSend.length > 255 ? '文字过长，限长255字符!' : ''
                  }
                >
                  <TextArea
                    placeholder="请输入内容"
                    style={{
                      background: 'rgba(255, 255, 255,.6)',
                      maxHeight: '300px',
                      height: '200px',
                      borderRadius: '12px'
                    }}
                    onChange={(e) =>
                      this.setState({ commentSend: e.target.value })
                    }
                    value={commentSend}
                  />
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                  <Button type="primary" htmlType="submit">
                    发送
                  </Button>
                </Form.Item>
              </Form>
            </div>
          </div>
        </div>
      </div>
    )
  }
}
export default memo(comments)
